using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.DescendantFiles;
using MediatR;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.DescendantFiles
{
    /// <summary>
    /// 后裔档案更新命令处理器
    /// </summary>
    public class UpdateDescendantFileCommandHandler : IRequestHandler<UpdateDescendantFileCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<DescendantFile> _descendantRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateDescendantFileCommandHandler> _logger;

        public UpdateDescendantFileCommandHandler(
            IBaseRepository<DescendantFile> descendantRepository,
            IMapper mapper,
            ILogger<UpdateDescendantFileCommandHandler> logger)
        {
            _descendantRepository = descendantRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理后裔档案更新命令
        /// </summary>
        /// <param name="request">后裔档案更新命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateDescendantFileCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("后裔档案更新请求参数为空");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "请求参数不能为空", data = false };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"后裔档案更新数据验证失败: {errorMessage}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = errorMessage, data = false };
                }

                // 根据ID查询后裔档案
                var descendantFile = await _descendantRepository.GetByIdAsync(request.DescendantId);
                
                if (descendantFile == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.DescendantId} 的后裔档案");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "未找到指定的后裔档案", data = false };
                }

                // 检查是否已被删除
                if (descendantFile.IsDeleted)
                {
                    _logger.LogWarning($"ID为 {request.DescendantId} 的后裔档案已被删除");
                    return new ApiResult<bool> { Code = ApiEnum.查询失败, Message = "后裔档案已被删除", data = false };
                }

                // 更新后裔档案信息
                descendantFile.EarSignal = request.EarSignal;
                descendantFile.ElectronicEarTag = request.ElectronicEarTag;
                descendantFile.FatherNumber = request.FatherNumber;
                descendantFile.MotherEarTag = request.MotherEarTag;
                descendantFile.Variety = request.Variety;
                descendantFile.Gender = request.Gender;
                descendantFile.BirthStatus = request.BirthStatus;
                descendantFile.DateofBirth = request.DateofBirth;
                descendantFile.EntryDate = request.EntryDate;
                descendantFile.PlaceOfBirth = request.PlaceOfBirth;
                descendantFile.BirthWeight = request.BirthWeight;
                descendantFile.GeneRank = request.GeneRank;
                descendantFile.Note = request.Note;
                
                // 执行更新
                var result = await _descendantRepository.UpdateAsync(descendantFile);
                
                if (result>0)
                {
                    _logger.LogInformation($"成功更新后裔档案，ID: {request.DescendantId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "后裔档案更新成功", data = true };
                }
                else
                {
                    _logger.LogError($"更新后裔档案失败，ID: {request.DescendantId}");
                    return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "后裔档案更新失败", data = false };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新后裔档案时发生系统异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = "系统异常，请联系管理员", data = false };
            }
        }
    }
}